Conditional Statements and Loops in JavaScript for React Native
Course: React Native Training
Topic: Conditional Statements and Loops
Course Link: React Native Training at JustAcademy
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Conditional Statements and Loops
Conditional statements and loops are fundamental concepts in JavaScript. They control the flow of a program by determining which instructions should execute and how many times a task should be repeated.
In React Native development, conditional statements are used to validate user input, display different screens or messages, check login status, handle application states, and manage errors. Loops and array iteration methods are used to process lists of products, students, notifications, and other data.
1.1 What Are Conditional Statements?
Conditional statements allow a program to execute different blocks of code depending on whether a condition is true or false.
Example:
const age = 20;
if (age >= 18) {
console.log("You are eligible.");
} else {
console.log("You are not eligible.");
}
Here, JavaScript checks whether age is greater than or equal to 18. Since the condition is true, the first message is displayed.
1.2 What Are Loops?
Loops repeatedly execute a block of code while a condition is satisfied or until a collection has been processed.
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
}
This loop displays numbers from 1 to 5. Instead of writing five separate print statements, a loop performs the repeated task efficiently.
1.3 Importance in React Native
- Check whether a user is logged in before displaying protected content.
- Validate forms and display error messages.
- Show loading, success, empty, and error states.
- Display different content based on user preferences.
- Process API responses and transform arrays of data.
- Render lists of products, contacts, messages, and notifications.
- Calculate totals, averages, discounts, and other values.
2. Understanding Conditions and Boolean Values
A condition is an expression that JavaScript evaluates to determine whether something is true or false. Comparisons and logical operators are commonly used to create conditions.
2.1 Boolean Values
JavaScript has two Boolean values: true and false.
const isLoggedIn = true;
const hasPermission = false;
console.log(isLoggedIn);
console.log(hasPermission);
2.2 Comparison Operators
| Operator |
Meaning |
Example |
Result |
== |
Loose equality |
5 == "5" |
true |
=== |
Strict equality |
5 === 5 |
true |
!= |
Loose inequality |
5 != 3 |
true |
!== |
Strict inequality |
5 !== "5" |
true |
> |
Greater than |
10 > 5 |
true |
< |
Less than |
3 < 8 |
true |
>= |
Greater than or equal to |
5 >= 5 |
true |
<= |
Less than or equal to |
4 <= 6 |
true |
Use === and !== in most cases because they avoid implicit type conversion during comparisons.
2.3 Logical Operators
| Operator |
Purpose |
Example |
&& |
Logical AND: both conditions must be true |
age >= 18 && hasID |
|| |
Logical OR: at least one condition must be true |
isAdmin || isManager |
! |
Logical NOT: reverses truthiness |
!isLoggedIn |
const age = 22;
const hasID = true;
if (age >= 18 && hasID) {
console.log("Access granted.");
} else {
console.log("Access denied.");
}
3. The if Statement
The if statement executes a block of code only when its condition evaluates to true.
3.1 Syntax
if (condition) {
// Code executes when the condition is true
}
3.2 Example: Checking Age
const age = 19;
if (age >= 18) {
console.log("You can register.");
}
If the age is at least 18, the message is displayed. If the condition is false, the code inside the block is skipped.
3.3 Example: Checking Stock Availability
const stock = 10;
if (stock > 0) {
console.log("Product is available.");
}
3.4 React Native Example
import { View, Text } from "react-native";
const WelcomeScreen = () => {
const isLoggedIn = true;
if (isLoggedIn) {
return (
<View>
<Text>Welcome back!</Text>
</View>
);
}
return (
<View>
<Text>Please log in.</Text>
</View>
);
};
export default WelcomeScreen;
The component checks the login status and returns the appropriate interface. In a real application, login status should be based on the application's authentication state rather than a hard-coded value.
4. The if...else Statement
The if...else statement provides two possible execution paths. One block runs if the condition is true, and the other runs if it is false.
4.1 Syntax
if (condition) {
// Executes if true
} else {
// Executes if false
}
4.2 Example: Pass or Fail
const marks = 45;
if (marks >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
4.3 Example: Online and Offline Status
const isOnline = false;
if (isOnline) {
console.log("You are online.");
} else {
console.log("You are offline.");
}
4.4 React Native Example: Connection Status
import { View, Text } from "react-native";
const ConnectionStatus = () => {
const isConnected = false;
if (isConnected) {
return (
<View>
<Text>Internet connection available.</Text>
</View>
);
}
return (
<View>
<Text>Please check your connection.</Text>
</View>
);
};
export default ConnectionStatus;
This example illustrates conditional UI. For actual connectivity detection, use an appropriate connectivity API or library and update the component based on its results.
5. The if...else if...else Statement
Use if...else if...else when there are multiple possible conditions. JavaScript checks the conditions from top to bottom and executes the first matching block.
5.1 Syntax
if (condition1) {
// First condition
} else if (condition2) {
// Second condition
} else if (condition3) {
// Third condition
} else {
// Default case
}
5.2 Example: Grading System
const marks = 82;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 60) {
console.log("Grade C");
} else if (marks >= 40) {
console.log("Grade D");
} else {
console.log("Fail");
}
Since the marks are 82, the output is Grade B.
5.3 Example: Discount Calculation
const purchaseAmount = 2500;
let discount = 0;
if (purchaseAmount >= 5000) {
discount = 20;
} else if (purchaseAmount >= 2000) {
discount = 10;
} else if (purchaseAmount >= 1000) {
discount = 5;
} else {
discount = 0;
}
console.log("Discount:", discount + "%");
5.4 Important Rule: Condition Order
Order conditions from the most specific or highest threshold to the broadest when appropriate. Otherwise, an earlier condition may match and prevent a later condition from running.
// Incorrect ordering
const marks = 95;
if (marks >= 40) {
console.log("Pass");
} else if (marks >= 90) {
console.log("Excellent");
}
The output is Pass, because the first condition already matches. The correct ordering is:
if (marks >= 90) {
console.log("Excellent");
} else if (marks >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}
6. Nested if Statements
A nested if statement is an if statement placed inside another conditional block. It is useful when a second condition should be checked only after the first condition succeeds.
6.1 Example: Login Validation
const username = "admin";
const password = "12345";
if (username === "admin") {
if (password === "12345") {
console.log("Login successful.");
} else {
console.log("Incorrect password.");
}
} else {
console.log("User not found.");
}
6.2 Example: Course Registration
const age = 21;
const hasCompletedPrerequisites = true;
if (age >= 18) {
if (hasCompletedPrerequisites) {
console.log("Registration allowed.");
} else {
console.log("Complete the prerequisites first.");
}
} else {
console.log("Minimum age requirement not met.");
}
6.3 Best Practices for Nested Conditions
- Use nesting only when the logic requires it.
- Avoid deeply nested conditions because they are harder to read.
- Consider combining related conditions with logical operators.
- Extract complicated checks into named functions.
- Never rely on hard-coded credentials for real authentication.
7. The switch Statement
The switch statement selects a code block based on the value of an expression. It can make code easier to read when several cases depend on the same variable.
7.1 Syntax
switch (expression) {
case value1:
// Statements
break;
case value2:
// Statements
break;
default:
// Default statements
}
7.2 Example: Navigation Menu Selection
const selectedTab = "profile";
switch (selectedTab) {
case "home":
console.log("Home screen selected");
break;
case "profile":
console.log("Profile screen selected");
break;
case "settings":
console.log("Settings screen selected");
break;
default:
console.log("Unknown tab");
}
7.3 Why Is break Important?
The break statement exits the switch block after a matching case. Without it, execution may continue into the following cases. This behavior is called fall-through and should be used intentionally only when desired.
7.4 Example: Application Status
const status = "loading";
switch (status) {
case "loading":
console.log("Please wait...");
break;
case "success":
console.log("Data loaded successfully.");
break;
case "error":
console.log("Unable to load data.");
break;
default:
console.log("Unknown status.");
}
This pattern is useful for handling common application states such as loading, success, and error.
8. The Ternary Operator
The ternary operator is a concise conditional expression that selects one of two values based on a condition.
8.1 Syntax
condition ? valueIfTrue : valueIfFalse;
8.2 Example
const age = 20;
const message = age >= 18
? "Eligible"
: "Not eligible";
console.log(message);
8.3 Conditional Rendering in React Native
import { View, Text } from "react-native";
const LoginMessage = () => {
const isLoggedIn = true;
return (
<View>
<Text>
{isLoggedIn ? "Welcome back!" : "Please log in."}
</Text>
</View>
);
};
export default LoginMessage;
8.4 Nested Ternary Operator
const marks = 76;
const grade = marks >= 90
? "A"
: marks >= 75
? "B"
: marks >= 50
? "C"
: "Fail";
console.log(grade);
Nested ternary operators can become difficult to understand. For complex business logic, use if...else if...else or a separate function instead.
9. Logical AND and OR for Conditional Rendering
Logical operators can be used in JSX to display content conditionally.
9.1 Using the AND Operator
The && operator is commonly used when content should appear only if a condition is true.
import { View, Text } from "react-native";
const NotificationMessage = () => {
const hasNotification = true;
return (
<View>
{hasNotification && (
<Text>You have a new notification.</Text>
)}
</View>
);
};
export default NotificationMessage;
9.2 Important Warning About Zero
In JavaScript, the && operator returns an operand, not necessarily a Boolean. If the left operand is zero, React Native may render the number 0 instead of rendering nothing.
const unreadCount = 0;
// Avoid this if zero should not appear:
{unreadCount && <Text>Unread messages</Text>}
// Safer:
{unreadCount > 0 && (
<Text>Unread messages</Text>
)}
9.3 Using the OR Operator
The || operator can provide a fallback value when the left-hand value is falsy.
const userName = "";
const displayName = userName || "Guest";
console.log(displayName); // Guest
Use ?? instead when the fallback should apply only to null or undefined, because || also treats values such as 0, false, and an empty string as falsy.
const quantity = 0;
const safeQuantity = quantity ?? 1;
const fallbackQuantity = quantity || 1;
console.log(safeQuantity); // 0
console.log(fallbackQuantity); // 1
10. Introduction to Loops
Loops execute statements repeatedly. A loop usually includes an initialization, a condition, and an update operation. The condition determines whether another iteration should occur.
10.1 Why Loops Are Useful
- Repeat calculations for multiple values.
- Search for a particular item in a collection.
- Process records and transform data.
- Generate a series of values.
- Perform repetitive tasks without duplicating code.
10.2 Main Types of JavaScript Loops
| Loop |
Typical Use |
for |
Repeat a known number of times or control the iteration counter. |
while |
Repeat while a condition remains true. |
do...while |
Execute the body at least once, then check the condition. |
for...of |
Iterate over values from arrays and other iterables. |
for...in |
Iterate over enumerable property keys, commonly for objects. |
11. The for Loop
The for loop is commonly used when the number of iterations is known or when the developer needs direct control over an iteration counter.
11.1 Syntax
for (initialization; condition; update) {
// Repeated statements
}
11.2 Example: Print Numbers
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Execution steps:
- Initialize
i to 1.
- Check whether
i <= 5.
- Execute the loop body if the condition is true.
- Increase
i by 1.
- Repeat until the condition becomes false.
11.3 Example: Calculate a Total
const prices = [100, 250, 150];
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
console.log("Total:", total); // 500
11.4 Example: Reverse Counting
for (let i = 5; i >= 1; i--) {
console.log(i);
}
11.5 Example: Even Numbers
for (let i = 2; i <= 20; i += 2) {
console.log(i);
}
12. The while Loop
The while loop repeatedly executes a block while its condition is true. It is useful when the number of repetitions is not known in advance.
12.1 Syntax
while (condition) {
// Repeated statements
}
12.2 Example: Counting
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
12.3 Example: Processing a Balance
let balance = 500;
let withdrawals = 0;
while (balance >= 100) {
balance -= 100;
withdrawals++;
}
console.log("Withdrawals:", withdrawals);
console.log("Remaining balance:", balance);
12.4 Avoid Infinite Loops
An infinite loop occurs when a loop's condition never becomes false. Always ensure that the loop can terminate.
// Incorrect: count never changes
// while (count <= 5) {
// console.log(count);
// }
// Correct:
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
13. The do...while Loop
The do...while loop executes its body once before checking the condition. Therefore, its body runs at least one time even when the condition is initially false.
13.1 Syntax
do {
// Statements execute first
} while (condition);
13.2 Example
let number = 10;
do {
console.log(number);
number++;
} while (number < 5);
The output is 10 because the loop body executes once before the condition is evaluated.
13.3 Comparison with while
let first = 10;
while (first < 5) {
console.log(first);
}
let second = 10;
do {
console.log(second);
} while (second < 5);
The while loop does not execute its body, but the do...while loop executes its body once.
14. The for...of Loop
The for...of loop iterates over values from an iterable, such as an array or string. It is useful when the value of each item matters more than its index.
14.1 Example with an Array
const courses = [
"JavaScript",
"React",
"React Native"
];
for (const course of courses) {
console.log(course);
}
14.2 Example with Product Prices
const prices = [250, 450, 700];
let total = 0;
for (const price of prices) {
total += price;
}
console.log("Total price:", total);
14.3 Example with a String
const appName = "React";
for (const character of appName) {
console.log(character);
}
Use for...of when you want to iterate over array values. Use an indexed for loop when you specifically need to work with the index or control the iteration step.
15. The for...in Loop
The for...in loop iterates over enumerable property keys of an object. It is commonly used to inspect object properties, but it is generally not the preferred way to iterate over array values.
15.1 Example with an Object
const student = {
name: "Riya",
age: 22,
course: "React Native"
};
for (const key in student) {
console.log(key, student[key]);
}
15.2 Using Object.entries()
Object.entries() returns an array of an object's own enumerable string-keyed property pairs. It can be convenient when both the key and value are needed.
const product = {
name: "Keyboard",
price: 1200,
inStock: true
};
for (const [key, value] of Object.entries(product)) {
console.log(`${key}: ${value}`);
}
15.3 for...in Versus for...of
| Feature |
for...in |
for...of |
| Iterates over |
Enumerable property keys |
Iterable values |
| Typical use |
Inspecting object keys |
Processing array values |
| Array example |
Returns index keys as strings |
Returns each array value |
| Common recommendation |
Use for object keys when suitable |
Use for iterable values |
16. break and continue Statements
The break and continue statements change the normal flow of a loop.
16.1 The break Statement
break immediately exits the nearest enclosing loop or switch statement.
for (let i = 1; i <= 10; i++) {
if (i === 6) {
break;
}
console.log(i);
}
The loop stops when i reaches 6, so the values 1 through 5 are printed.
16.2 Example: Find a Product
const productIds = [101, 102, 103, 104];
const targetId = 103;
for (const id of productIds) {
if (id === targetId) {
console.log("Product found:", id);
break;
}
}
16.3 The continue Statement
continue skips the rest of the current iteration and moves to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
The output is 1, 2, 4, and 5. The number 3 is skipped.
16.4 Example: Skip Out-of-Stock Products
const products = [
{ name: "Mouse", inStock: true },
{ name: "Keyboard", inStock: false },
{ name: "Monitor", inStock: true }
];
for (const product of products) {
if (!product.inStock) {
continue;
}
console.log(product.name);
}
17. Array Iteration Methods: map(), filter(), and forEach()
In React Native applications, arrays are frequently processed using built-in array methods. These methods often provide readable alternatives to traditional loops.
17.1 The forEach() Method
forEach() runs a callback for every array element. It is useful for performing an action for each item, but it does not return a new transformed array.
const names = ["Riya", "Aman", "Neha"];
names.forEach(name => {
console.log(name);
});
17.2 The map() Method
map() transforms every item and returns a new array containing the callback results.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
console.log(doubled); // [2, 4, 6, 8]
17.3 The filter() Method
filter() returns a new array containing only the elements that pass a condition.
const ages = [12, 18, 25, 15, 30];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 25, 30]
17.4 The find() Method
find() returns the first array element that satisfies a condition, or undefined if no element matches.
const products = [
{ id: 1, name: "Mouse" },
{ id: 2, name: "Keyboard" },
{ id: 3, name: "Monitor" }
];
const selectedProduct = products.find(
product => product.id === 2
);
console.log(selectedProduct);
17.5 The reduce() Method
reduce() combines array values into a single result, such as a total, average calculation input, or grouped structure.
const prices = [100, 200, 300];
const total = prices.reduce(
(sum, price) => sum + price,
0
);
console.log(total); // 600
17.6 Choosing the Right Method
| Method |
Purpose |
Return Value |
forEach() |
Perform an action for each item |
Undefined |
map() |
Transform each item |
New array |
filter() |
Select matching items |
New array |
find() |
Find the first matching item |
Item or undefined |
reduce() |
Combine values into one result |
Accumulated result |
18. Rendering Lists in React Native
React Native applications commonly display data from arrays. JavaScript's map() method can transform each item into a React element. For larger or changing lists, FlatList is generally a better choice because it supports efficient list rendering.
18.1 Rendering an Array with map()
import { View, Text } from "react-native";
const names = ["Riya", "Aman", "Neha"];
const NameList = () => {
return (
<View>
{names.map(name => (
<Text key={name}>{name}</Text>
))}
</View>
);
};
export default NameList;
Each item has a key so React can identify it among its siblings. For dynamic data, prefer a stable, unique identifier from the data source rather than relying on an item's position.
18.2 Rendering Products with FlatList
import { View, Text, FlatList } from "react-native";
const products = [
{ id: "1", name: "Mouse", price: 500 },
{ id: "2", name: "Keyboard", price: 1200 },
{ id: "3", name: "Monitor", price: 8000 }
];
const ProductList = () => {
return (
<FlatList
data={products}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>Price: ₹{item.price}</Text>
</View>
)}
/>
);
};
export default ProductList;
18.3 Conditionally Displaying an Empty Message
import { View, Text, FlatList } from "react-native";
const tasks = [];
const TaskList = () => {
return (
<View>
{tasks.length === 0 ? (
<Text>No tasks available.</Text>
) : (
<FlatList
data={tasks}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<Text>{item.title}</Text>
)}
/>
)}
</View>
);
};
export default TaskList;
19. Combining Conditional Statements and Loops
Conditional statements and loops often work together. A loop processes multiple items, while a condition determines what should happen for each item.
19.1 Example: Find Even Numbers
const numbers = [1, 2, 3, 4, 5, 6];
for (const number of numbers) {
if (number % 2 === 0) {
console.log(number);
}
}
19.2 Example: Categorize Products
const products = [
{ name: "Mouse", price: 500 },
{ name: "Keyboard", price: 1500 },
{ name: "Monitor", price: 9000 }
];
for (const product of products) {
if (product.price >= 5000) {
console.log(product.name, "is expensive");
} else {
console.log(product.name, "is affordable");
}
}
19.3 Example: Count Passed Students
const marks = [85, 42, 67, 30, 91];
let passedCount = 0;
for (const mark of marks) {
if (mark >= 50) {
passedCount++;
}
}
console.log("Students passed:", passedCount);
19.4 Example: Filter and Display Available Items
const products = [
{ id: 1, name: "Mouse", available: true },
{ id: 2, name: "Keyboard", available: false },
{ id: 3, name: "Headphones", available: true }
];
const availableProducts = products.filter(
product => product.available
);
availableProducts.forEach(product => {
console.log(product.name);
});
20. Conditional Rendering for Loading, Success, and Error States
Mobile applications often need to show different interfaces while data is loading, after a successful response, or when an operation fails. Conditional statements help present the correct UI for each state.
import { View, Text, ActivityIndicator } from "react-native";
const DataStatus = ({ status, message }) => {
if (status === "loading") {
return (
<View>
<ActivityIndicator />
<Text>Loading data...</Text>
</View>
);
}
if (status === "error") {
return (
<View>
<Text>Unable to load data.</Text>
</View>
);
}
if (status === "success") {
return (
<View>
<Text>{message}</Text>
</View>
);
}
return (
<View>
<Text>Waiting to start.</Text>
</View>
);
};
export default DataStatus;
In this example, the component returns a different interface depending on the status prop. The parent component is responsible for providing the current status and any relevant message.
21. Loop Control and Performance Considerations
Loops and array methods are useful, but they should be chosen according to the task and data size. Inefficient repeated work can make an application feel slow, particularly when it occurs during rendering.
21.1 Avoid Unnecessary Work During Rendering
- Keep calculations simple inside components when possible.
- Move complex reusable logic into clearly named functions.
- Use list components such as
FlatList for long lists.
- Avoid repeatedly processing large datasets when the inputs have not changed, unless necessary.
- Measure actual performance before adding optimization techniques.
21.2 Avoid Mutating Arrays Unexpectedly
const originalNumbers = [1, 2, 3];
// Creates a new array
const updatedNumbers = [...originalNumbers, 4];
console.log(originalNumbers); // [1, 2, 3]
console.log(updatedNumbers); // [1, 2, 3, 4]
Creating new arrays and objects is particularly important when updating React state, because state updates should represent changes with new values rather than unexpected direct mutations.
21.3 Use the Appropriate Iteration Method
- Use
for when you need precise control over the index or iteration step.
- Use
for...of when you need to process iterable values.
- Use
map() to transform data into a new array.
- Use
filter() to select matching elements.
- Use
find() when you need the first matching element.
- Use
FlatList when rendering larger lists of React Native elements.
22. Common Mistakes and Troubleshooting
| Mistake |
Why It Happens |
Solution |
Using = instead of === |
Assignment is confused with comparison |
Use comparison operators in conditions. |
| Incorrect condition order |
A broad condition matches before a specific one |
Arrange conditions carefully, usually from the highest threshold to the lowest. |
Missing break in switch |
Execution falls through to later cases |
Add break unless fall-through is intentional. |
| Infinite loop |
The loop condition never becomes false |
Check that the loop variable or condition changes appropriately. |
| Off-by-one error |
The starting or ending condition is incorrect |
Review the loop boundaries and array length. |
Using for...in for array values |
The developer expects values but receives keys |
Use for...of or an appropriate array method. |
| Rendering zero unexpectedly |
A numeric zero is used as the left side of && |
Use an explicit condition such as count > 0. |
| Missing React keys |
Mapped elements have no stable identity |
Supply unique, stable keys for rendered items. |
| Too many nested ternaries |
Complex conditions are compressed into one expression |
Use if statements or a separate function. |
| Directly modifying state arrays |
Existing state is mutated instead of creating a new value |
Use the state setter with a new array or object. |
23. Best Practices
- Use
if...else for straightforward conditional logic.
- Use
switch when several cases depend on the same value.
- Use the ternary operator for simple two-way expressions.
- Use
&& for conditional rendering when no alternative is needed, but avoid accidentally rendering zero.
- Keep nested conditions readable and avoid unnecessary complexity.
- Choose loop types based on the data and task.
- Always check loop termination conditions.
- Prefer descriptive names for conditions, counters, and callback parameters.
- Use stable keys when rendering arrays of React components.
- Use
FlatList for larger React Native lists.
- Handle loading, empty, success, and error states in data-driven screens.
- Test edge cases, including empty arrays, zero values, missing data, and unexpected input.
24. Hands-On Exercises
Exercise 1: Positive, Negative, or Zero
Create a variable called number. Use if...else if...else to display whether the number is positive, negative, or zero.
Exercise 2: Age Eligibility
Create an age variable. Display an appropriate message depending on whether the person is under 18 or at least 18 years old.
Exercise 3: Grade Calculator
Use a marks variable and conditional statements to assign grades according to a grading scale of your choice. Make sure the conditions are in the correct order.
Exercise 4: Multiplication Table
Use a for loop to display the multiplication table of a number from 1 through 10.
Exercise 5: Sum of Array Values
Create an array of numbers and use a loop to calculate their total.
Exercise 6: Filter Available Products
Create an array of product objects with a name and availability status. Use filter() to select available products.
Exercise 7: Skip Odd Numbers
Use a loop and continue to display only even numbers from 1 through 20.
Exercise 8: React Native Conditional Message
Create a component that displays a welcome message when a Boolean prop is true and a login prompt otherwise.
Exercise 9: Student List
Create an array of student objects and display the names using map() or FlatList. Give each item a unique key.
25. Mini Project: Product Inventory Screen
Project Objective: Build a simple React Native screen that displays products, identifies items in stock, and calculates the number of available products.
Project Requirements
- Create an array of product objects.
- Each product should contain an ID, name, price, and availability status.
- Use
filter() to find available products.
- Use a conditional statement to display an empty message when no products are available.
- Use
map() or FlatList to display the product list.
- Use a conditional expression to display the stock status.
- Display the number of available products.
Sample Implementation
import { View, Text, FlatList } from "react-native";
const products = [
{ id: "1", name: "Mouse", price: 500, inStock: true },
{ id: "2", name: "Keyboard", price: 1200, inStock: false },
{ id: "3", name: "Headphones", price: 1800, inStock: true }
];
const availableProducts = products.filter(
product => product.inStock
);
const ProductInventory = () => {
return (
<View>
<Text>
Available Products: {availableProducts.length}
</Text>
{availableProducts.length === 0 ? (
<Text>No products available.</Text>
) : (
<FlatList
data={products}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>Price: ₹{item.price}</Text>
<Text>
{item.inStock ? "In Stock" : "Out of Stock"}
</Text>
</View>
)}
/>
)}
</View>
);
};
export default ProductInventory;
Note: This example displays all products and uses a filtered array to calculate the number of available products. To display only available products, change the FlatList data prop to availableProducts.
Expected Learning Outcomes
- Apply conditions to control the displayed content.
- Use loops and array methods to process collections.
- Render data with React Native components.
- Display different messages based on data availability.
- Combine JavaScript logic with JSX.
26. Interview Questions and Answers
Q1. What are conditional statements in JavaScript?
Answer: Conditional statements control program execution based on whether conditions are true or false. Examples include if, if...else, and switch.
Q2. What is the difference between if and if...else?
Answer: An if statement executes a block only when its condition is true. An if...else statement provides an alternative block when the condition is false.
Q3. What is an else if statement?
Answer: An else if statement checks another condition when earlier conditions were false. It supports multiple alternative paths.
Q4. What is a nested if statement?
Answer: A nested if statement is an if statement inside another conditional block. It is useful when one condition should be evaluated only after another condition succeeds.
Q5. What is a switch statement?
Answer: A switch statement selects a case based on an expression's value. It is often useful for handling several known status values.
Q6. What is the ternary operator?
Answer: The ternary operator is a conditional expression written as condition ? valueIfTrue : valueIfFalse. It is commonly used for simple conditional expressions and JSX rendering.
Q7. What is the difference between for and while loops?
Answer: A for loop puts initialization, condition, and update expressions together. A while loop checks a condition before each iteration and is useful when the number of repetitions is not known in advance.
Q8. What is the difference between while and do...while?
Answer: A while loop checks the condition before executing its body. A do...while loop executes the body first, so it always runs at least once.
Q9. What is the difference between for...in and for...of?
Answer: for...in iterates over enumerable property keys, while for...of iterates over values from an iterable such as an array.
Q10. What does break do?
Answer: The break statement exits the nearest enclosing loop or switch statement.
Q11. What does continue do?
Answer: The continue statement skips the remaining code in the current loop iteration and moves to the next iteration.
Q12. What is an infinite loop?
Answer: An infinite loop continues indefinitely because its termination condition never becomes false or the loop never reaches a terminating statement.
Q13. What is the difference between map() and forEach()?
Answer: map() returns a new array containing transformed items. forEach() executes a callback for each item and returns undefined.
Q14. How are loops used in React Native?
Answer: Loops and array methods process application data. In JSX, map() is commonly used to create elements from arrays, while FlatList is suitable for efficiently rendering larger lists.
Q15. How can a React Native component show different content based on a condition?
Answer: It can use an if statement to return different JSX, a ternary expression for two alternatives, or logical && when content should appear only when a condition is true.
27. Quick Revision Checklist
- Understand Boolean values and comparison operators.
- Practice
if, if...else, and else if.
- Know how nested conditions work.
- Use
switch and understand break.
- Use ternary expressions for simple two-way decisions.
- Understand conditional rendering with
&& and ||.
- Practice
for, while, and do...while.
- Know the difference between
for...in and for...of.
- Use
break and continue appropriately.
- Understand
map(), filter(), find(), and forEach().
- Render lists with stable keys or use
FlatList.
- Test empty arrays, boundary values, and unexpected data.
28. Recommended Learning Resources
29. Conclusion
Conditional statements and loops are essential building blocks of JavaScript and React Native development. Conditional statements help applications make decisions and display the correct interface, while loops and array methods help process data efficiently.
By practicing if...else, switch, ternary expressions, for, while, for...of, map(), and filter(), developers can build dynamic mobile interfaces, process API data, validate user input, and manage lists.
Continue practicing with small JavaScript exercises before combining these concepts in complete React Native projects. Focus on readable conditions, correct loop boundaries, stable list keys, and appropriate handling of empty or unexpected data.
Continue Learning: Explore React Native Training | Register for a Demo